package com.gcd.api;


import com.gcd.model.Member;
import com.gcd.service.LoginService;
import com.gcd.utils.JsonResult;
import com.gcd.utils.JwtUtil;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/login")
public class LoginApi {
    private final static StrongPasswordEncryptor PE = new StrongPasswordEncryptor();
    private LoginService loginService;
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    @PostMapping
    public ResponseEntity<JsonResult<?>> login(@RequestBody Member member) {
        try {
            if (member.getPhone() == null || member.getPassword() == null) {
                return ResponseEntity.ok(JsonResult.fail("手机号和密码不能为空"));
            }

            Member member1 = loginService.findByPhone(member.getPhone());
            if (member1 == null) {
                return ResponseEntity.ok(JsonResult.fail("用户不存在"));
            }
            boolean pass = PE.checkPassword(member.getPassword(), member1.getPassword());
            if (!pass) {
                return ResponseEntity.ok(JsonResult.fail("密码错误"));
            }
            String jwt = JwtUtil.createJwt(UUID.randomUUID().toString(), member1.getPhone(),
                    Map.of("username", member1.getPhone(), "userId", member1.getId()),
                    LocalDateTime.now().plusMinutes(300), jwtSecret);
            return ResponseEntity.ok(JsonResult.success(jwt));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(JsonResult.fail("登录过程中发生错误: " + e.getMessage()));
        }
    }

}
